
package com.xc.smart.interceptor;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xc.smart.annotation.LoginUser;
import com.xc.smart.entity.User;
import com.xc.smart.jwt.JWTService;
import com.xc.smart.utlis.Constants;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@LoginUser注解的方法参数，注入当前登录用户
 * @author Admin
 */
@Configuration
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    JWTService jwtService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(User.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory){
        //获取用户ID
        String token = request.getHeader(AuthorizationInterceptor.TOKEN_NAME);
        if(StringUtils.isBlank(token)){
            return null;
        }
        Claims claims = jwtService.parseToken(token);
        Object user = claims.get(Constants.USER_KEY);

        com.xc.smart.entity.LoginUser loginUser = BeanUtil.copyProperties(user, com.xc.smart.entity.LoginUser.class);

        if(loginUser==null){
            return null;
        }

        return loginUser.getUser();
    }
}
